package com.wt.struggle.goodbye.main.activity

import android.content.ContentValues
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.media.MediaPlayer
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ImageView
import android.widget.LinearLayout
import com.wt.struggle.goodbye.R
import com.wt.struggle.goodbye.base.Config
import com.wt.struggle.goodbye.base.ItemClickListener
import com.wt.struggle.goodbye.base.ProActivity
import com.wt.struggle.goodbye.base.Share
import com.wt.struggle.goodbye.info.NetInfo
import com.wt.struggle.goodbye.info.NewsInfo
import com.wt.struggle.goodbye.info.VideoInfo
import com.wt.struggle.goodbye.sq.adapter.ContentImageAdapter
import com.wt.struggle.goodbye.user.activity.ShowImageActivity
import com.xin.lv.yang.utils.utils.DataUtil
import com.xin.lv.yang.utils.utils.ImageUtil
import kotlinx.android.synthetic.main.head.*
import kotlinx.android.synthetic.main.pick_user_item.*
import kotlinx.android.synthetic.main.tie_details_layout.*

/**
 * 帖子详情
 */
class TieDetailsActivity : ProActivity() {

    override fun handler(what: Int, arg1: Int, netInfo: NetInfo) {

    }

    /**
     *  2 为轮播图跳转     1 为帖子详情跳转
     *
     */
    var code: Int = 1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.tie_details_layout)

        tvTitle.text = "帖子详情"

        imageBack.setOnClickListener {
            finish()
        }

        code = intent.getIntExtra("code", 1)

        val info = intent.getParcelableExtra<NewsInfo>("data")

        if (code == 1) {

            detailsLinear.visibility = View.VISIBLE
            webView.visibility = View.GONE

            showDetails(info)

        } else if (code == 2) {

            webView.visibility = View.VISIBLE
            detailsLinear.visibility = View.GONE

            val url = "${Config.IP}/wap/content/contentDetail?id=${info.toId}&uuid=${Share.getUUID(this)}"

            log("webView路径--------$url")

            webView.loadUrl(url)
            val set = webView.settings
            set.javaScriptEnabled = true
            set.cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK

            webView.webViewClient = object : WebViewClient() {

            }

            webView.webChromeClient = object : WebChromeClient() {

            }
        }


        /// 加入历史记录
        send!!.addHistoryList(
            if (code == 1) {
                info.id
            } else {
                info.toId
            }, handler
        )

    }


    var isOpen = false

    private fun showDetails(info: NewsInfo) {
        tvContentMs.setSingleLine(false)
        tvContentMs.ellipsize = null

        tvFocusOn.visibility = View.GONE
        imgMoreFocus.visibility = View.GONE

        val videoList = info.videoList
        val voiceList = info.audioList

        if (videoList != null && videoList.size != 0) {

            val videoInfo = videoList[0]

            showVideo(videoInfo)

        } else if (info.pics != null && info.pics != "") {
            showPic(info)

        } else {
            if (voiceList != null && voiceList.size != 0) {
                val voiceInfo = voiceList[0]
                showVoice(voiceInfo)
            }

        }

//        val nameColor = info.topicColor
//
//        if (nameColor != null && nameColor != ""
//            && nameColor != "null"
//            && (nameColor.length == 6 || nameColor.length == 8)) {
//
//            tvContentMs.setTextColor(Color.parseColor("#$nameColor"))
//
//        }

        tvContentName.text = info.topicName
        tvContentMs.text = DataUtil.getEmoji(this,info.content)
        tvTextCollect.text = info.collectionCount.toString()
        tvZanNumber.text = info.likeCount.toString()
        tvDownZanNum.text = "0"
        tvCommentNum.text = info.commentCount.toString()

        if (info.location != "") {
            tvUserAddress.text = info.location
            linearIndex.visibility = View.VISIBLE
        } else {
            linearIndex.visibility = View.GONE
        }

        val userInfo = info.userExtraInfo

        if (userInfo != null) {
            ImageUtil.getInstance().loadCircleImage(this, sendImageUserHead, userInfo.avatarurl, 0)
            tvUserName.text = userInfo.nickName

            if (userInfo.isCollection == 1) {
                tvFocusOn.setBackgroundResource(R.drawable.gray_solid)
                tvFocusOn.setTextColor(resources.getColor(R.color.gray))
                tvFocusOn.text = "已关注"

            } else {
                tvFocusOn.setBackgroundResource(R.drawable.red_kuang_line)
                tvFocusOn.setTextColor(resources.getColor(R.color.red))
                tvFocusOn.text = "+关注"
            }

        }

        if (info.isCollection == 1) {

            imageCollect.setImageBitmap(BitmapFactory.decodeResource(resources, R.drawable.coll_y))
            tvTextCollect.setTextColor(resources.getColor(R.color.red))

        } else {
            imageCollect.setImageBitmap(BitmapFactory.decodeResource(resources, R.drawable.coll_n))
            tvTextCollect.setTextColor(resources.getColor(R.color.black777))
        }


        if (info.isLike == 1) {

            imageViewZan.setImageBitmap(BitmapFactory.decodeResource(resources, R.drawable.zan_y))
            tvZanNumber.setTextColor(resources.getColor(R.color.red))

        } else {
            imageViewZan.setImageBitmap(BitmapFactory.decodeResource(resources, R.drawable.zan_n))
            tvZanNumber.setTextColor(resources.getColor(R.color.black777))
        }


    }


    /**
     * 显示图片
     */
    private fun showPic(info: NewsInfo) {
        layoutImageRecyclerView.visibility = View.VISIBLE
        videoParentFrame.visibility = View.GONE
        voiceLinearLayout.visibility = View.GONE

        val picListArr = info.picList

        layoutImageRecyclerView.isNestedScrollingEnabled = false

        if (picListArr != null && picListArr.size != 0) {

            val len = picListArr.size

            if (len != 0) {
                when (len) {
                    1 -> layoutImageRecyclerView.layoutManager = GridLayoutManager(this, 1)
                    2 -> layoutImageRecyclerView.layoutManager = GridLayoutManager(this, 2)
                    else -> layoutImageRecyclerView.layoutManager = GridLayoutManager(this, 3)

                }

                val picAdapter = ContentImageAdapter(this, picListArr,len, 1)

                layoutImageRecyclerView.adapter = picAdapter

                picAdapter.itemClickListener = object : ItemClickListener {

                    override fun onItemClick(position: Int) {

                        val strArr = arrayListOf<String>()
                        for (temp in picListArr) {
                            strArr.add(temp.domainname + temp.path.subSequence(1, temp.path.length))
                        }

                        val intent = Intent(this@TieDetailsActivity, ShowImageActivity::class.java)
                        intent.putStringArrayListExtra("arr", strArr)
                        startActivity(intent)
                    }

                    override fun onLongClick(position: Int) {
                    }

                }

            }
        }

    }


    var isFull = false

    /**
     * 显示视频
     */
    private fun showVideo(info: VideoInfo) {

        layoutImageRecyclerView.visibility = View.GONE
        videoParentFrame.visibility = View.VISIBLE
        voiceLinearLayout.visibility = View.GONE

        val path = info.domainname + info.path

        standardGSYVideoPlayer.clearThumbImageView()

        val imageView = ImageView(this)
        imageView.scaleType = ImageView.ScaleType.CENTER_CROP


        ImageUtil.getInstance().loadVideoScreenshot(this, path, imageView,0, null)

        standardGSYVideoPlayer.thumbImageView = imageView


        standardGSYVideoPlayer.setUpLazy(path, true, null, null, "")
        standardGSYVideoPlayer.titleTextView.visibility = View.GONE
        standardGSYVideoPlayer.backButton.visibility = View.GONE

        standardGSYVideoPlayer.onBackFullscreen()

        //设置全屏按键功能
        standardGSYVideoPlayer.fullscreenButton.setOnClickListener {
            standardGSYVideoPlayer.startWindowFullscreen(this, false, true)
            isFull = true
        }

        //防止错位设置
        standardGSYVideoPlayer.playTag = ContentValues.TAG

        //是否根据视频尺寸，自动选择竖屏全屏或者横屏全屏
        standardGSYVideoPlayer.isAutoFullWithSize = true
        //音频焦点冲突时是否释放
        standardGSYVideoPlayer.isReleaseWhenLossAudio = false
        //全屏动画
        standardGSYVideoPlayer.isShowFullAnimation = true
        //小屏时不触摸滑动
        standardGSYVideoPlayer.setIsTouchWiget(false)

    }


    /**
     * 显示音频
     */
    private fun showVoice(voiceInfo: VideoInfo) {
        layoutImageRecyclerView.visibility = View.GONE
        videoParentFrame.visibility = View.GONE
        voiceLinearLayout.visibility = View.VISIBLE

        imageVoice.setOnClickListener {
            ///  播放音频
            ///  播放音频
            val mediaPlayer = MediaPlayer()
            mediaPlayer.setDataSource(voiceInfo.domainname + voiceInfo.path)

            mediaPlayer.prepare()

            mediaPlayer.start()

        }

    }
}